package net.ufrog.common.spring.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import net.ufrog.common.utils.Strings;
import net.ufrog.common.web.RequestParam;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2017-02-03
 * @since 0.1
 */
public class FastJsonpHttpMessageConverter extends FastJsonHttpMessageConverter4 {

    /** 参数代码 */
    private String jsonp = "jsonp";

    @Override
    protected void writeInternal(Object obj, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        HttpHeaders httpHeaders = outputMessage.getHeaders();
        OutputStream outputStream = outputMessage.getBody();

        RequestParam requestParam = RequestParam.current();
        String callback = requestParam.getValue(getJsonp());
        SerializeConfig serializeConfig = getFastJsonConfig().getSerializeConfig();
        SerializeFilter[] serializeFilters = getFastJsonConfig().getSerializeFilters();
        SerializerFeature[] serializerFeatures = getFastJsonConfig().getSerializerFeatures();
        String json = JSON.toJSONString(obj, serializeConfig, serializeFilters, getFastJsonConfig().getDateFormat(), JSON.DEFAULT_GENERATE_FEATURE, serializerFeatures);

        if (!Strings.empty(callback)) {
            json = callback + "(" + json + ")";
        }
        byte[] bytes = json.getBytes(getFastJsonConfig().getCharset());
        httpHeaders.setContentLength(bytes.length);
        outputStream.write(bytes);
    }

    /**
     * 读取参数代码
     *
     * @return 参数代码
     */
    public String getJsonp() {
        return jsonp;
    }

    /**
     * 设置参数代码
     *
     * @param jsonp 参数代码
     */
    public void setJsonp(String jsonp) {
        this.jsonp = jsonp;
    }
}
